package com.glamour.hlcity.dal.typeHandler;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.sql.Blob;
import java.sql.SQLException;
import java.sql.Types;

import com.ibatis.sqlmap.client.extensions.ParameterSetter;
import com.ibatis.sqlmap.client.extensions.ResultGetter;
import com.ibatis.sqlmap.client.extensions.TypeHandlerCallback;

/**
 * 将对象实例序列化
 * @author zhaoxing.liuzx
 *
 */
public class SerializableToBlobTypeHandler implements TypeHandlerCallback {

	public Object getResult(ResultGetter getter) throws SQLException{
		Blob blob = getter.getBlob();
		byte[] returnValue = null;
		if (null != blob) {
			returnValue = blob.getBytes(1, (int) blob.length());
			return converBytes(returnValue);
		} else {
			return null;
		}
	}

	public void setParameter(ParameterSetter setter, Object parameter) throws SQLException{
		if (null != parameter) {
			byte[] bytes = converSerializable((Serializable)parameter);
			ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
			setter.setBinaryStream(bis, (int) (bytes.length));
		}
		else{
			setter.setNull(Types.BLOB);
		}
		
	}

	public Object valueOf(String s) {
		return s;
	}
	
	/**
	 * 将obj转换为byte[]
	 * @param obj
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	byte[] converSerializable(Serializable obj) {
		try {
			ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
			ObjectOutputStream outputStream = new ObjectOutputStream(
					byteOutputStream);
			outputStream.writeObject(obj);
			byte[] byts = byteOutputStream.toByteArray();
			outputStream.close();
			byteOutputStream.close();
			return byts;
		} catch (Exception e) {
			throw new IllegalArgumentException(e);
		}
	}

	/**
	 * 将byte[]转换为obj
	 * @param byts
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	Serializable converBytes(byte[] byts) {
		try {
			ObjectInputStream inputStream = new ObjectInputStream(
					new ByteArrayInputStream(byts));
			Serializable obj = (Serializable) inputStream.readObject();
			inputStream.close();
			return obj;
		} catch (Exception e) {
			throw new IllegalArgumentException(e);
		}
	}
}
